package com.gxgeek.springweb.filter;

import com.alibaba.fastjson.JSON;
import com.gxgeek.springweb.model.BaseRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ContentCachingResponseWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author gxgeek
 * @create 2018-09-26 下午8:35
 */
@Slf4j
@Component
public class LogContentFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        BaseRequestWrapper requestWrapper = new BaseRequestWrapper((HttpServletRequest) servletRequest);

        String reqContent = IOUtils.toString(requestWrapper.getInputStream(), servletRequest.getCharacterEncoding());
        HashMap<Object, Object> headerMap = new HashMap<>();
        Enumeration<String> headerNames = requestWrapper.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            headerMap.put(headerName, requestWrapper.getHeader(headerName));
        }
        HashMap<String, String> parameterMap = requestWrapper.getParameterMap().entrySet().stream().collect(
                HashMap::new,
                ((map, entry) -> {
                    String vaule = Arrays.stream(entry.getValue())
                            .filter(s -> !StringUtils.isEmpty(s))
                            .collect(Collectors.joining(","));
                    map.put(entry.getKey(), String.join(",", vaule));
//                    map.put(entry.getKey(),  entry.getValue()[0]);
                }), Map::putAll);
        log.info("输入 body部分:{}" , reqContent);
        log.info("输入 heard部分:{}",headerMap );
        log.info("输入 paramer部分:{}", JSON.toJSONString(parameterMap));

        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);


        filterChain.doFilter(requestWrapper, responseWrapper);
        servletResponse.getOutputStream().write(responseWrapper.getContentAsByteArray());//最后注意需要请reponsewrapper的内容写入到原始response
//        responseWrapper.copyBodyToResponse(); // 直接输出

        String rspcontent = IOUtils.toString(responseWrapper.getContentInputStream(), servletRequest.getCharacterEncoding());
        log.info("返回:{}", rspcontent);

    }

    @Override
    public void destroy() {

    }
}
